package pl.jad.database.table.column;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import pl.jad.database.table.Table;

/**
 * Kolumna reprezentujaca indeks (unikalny w skali tabeli)
 *
 */
public class IndexTableColumn extends AbstractIndexTableColumn {
	/**
	 * Field used only for creating proper column type
	 */
	// FIXME: moze byc konflikt z polem zapisywanych klas
	protected int ___index___ = 1;
	
	public IndexTableColumn(Table table) throws Exception {
		super(table, IndexTableColumn.class.getDeclaredField("___index___"));
	}
	
	protected int getNextIndex() throws Exception {
		String sql = "SELECT MAX(___index___) FROM `" + this._table.getName() + "`;";
		ResultSet rs;
		try {
			Statement stmt = _table.getConnection().createStatement();
			rs = stmt.executeQuery(sql);
			rs.next();
			int currentId = rs.getInt(1);
			_Log.info("Current max index value = " + currentId);
			return ++currentId;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			throw new Exception("Could not read index column value using: " + sql + " " + e.getMessage());
		}
	}
	
	// this field does not exists in object
	public String getSqlFieldValue(Object object) throws Exception {
		this.___index___ = getNextIndex();
		return Integer.toString(this.___index___);
	}
	
	public int getIndex() {
		return this.___index___;
	}
}
